const app = getApp();

Page({
  data: {
    inputUrl: '',
    videoInfo: null,
    isLoading: false,
    historyList: [],
    currentVideo: null,
    platform: null,
    remainingCount: 3,
    isVipUser: false,
    homeImagePath: '/images/home.svg', // 新增图片路径
    videoToolImagePath: '/images/video_tool.png', // 新增图片路径
    myImagePath: '/images/my.png', // 新增图片路径
    videoUrl: '',
    videoAd: null,
    isAdLoaded: false,
    isDownloading: false,
    downloadProgress: 0,
    downloadTypes: [
      { name: '普通下载', type: 'normal' },
      { name: '无水印下载', type: 'noWatermark' }
    ],
    showAnalysis: false,
  },

  onLoad() {
    this.loadHistory()
    this.loadUserStatus()
    this.initVideoAd()
  },

  onShow() {
    this.loadHistory()
    this.loadUserStatus()
  },

  // 输入框变化
  onInputChange(e) {
    this.setData({
      inputUrl: e.detail.value
    })
  },

  // 解析视频
  parseVideo() {
    if (!this.data.inputUrl) {
      wx.showToast({
        title: '请输入视频链接',
        icon: 'none'
      });
      return;
    }

    this.setData({ isLoading: true });

    const apiUrl = 'https://douyin.wtf/api/hybrid/video_data';
    const encodedUrl = encodeURIComponent(this.data.inputUrl);
    const requestUrl = `${apiUrl}?url=${encodedUrl}&minimal=false`;

    wx.request({
      url: requestUrl,
      method: 'GET',
      header: {
        'accept': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200 && res.data.data) {
          const videoData = res.data.data;
          const highestQualityVideo = this.getHighestQualityVideo(videoData.video);
          
          if (highestQualityVideo) {
            // 格式化发布时间
            const createTime = new Date(videoData.create_time * 1000);
            const create_time_format = createTime.toLocaleString();

            const videoInfo = {
              url: highestQualityVideo.play_addr.url_list[0],
              cover: videoData.video.cover.url_list[0],
              title: videoData.desc || '未知标题',
              author: {
                nickname: videoData.author.nickname || '未知作者',
                avatar: videoData.author.avatar_thumb.url_list[0],
                signature: videoData.author.signature || ''
              },
              stats: {
                digg_count: this.formatNumber(videoData.statistics.digg_count),
                comment_count: this.formatNumber(videoData.statistics.comment_count),
                collect_count: this.formatNumber(videoData.statistics.collect_count),
                share_count: this.formatNumber(videoData.statistics.share_count)
              },
              platform: '抖音',
              create_time_format,
              text_extra: videoData.text_extra || [],
              music: videoData.music,
              time: new Date().toLocaleString()
            };

            this.setData({ 
              videoInfo: videoInfo, 
              currentVideo: videoInfo,
              showAnalysis: true // 自动显示分析面板
            });
            this.addToHistory(videoInfo);
            
            wx.showToast({
              title: '解析成功',
              icon: 'success'
            });
          } else {
            wx.showToast({
              title: '未找到可用的视频源',
              icon: 'none'
            });
          }
        } else {
          wx.showToast({
            title: res.data.message || '解析失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.error('解析失败:', error);
        wx.showToast({
          title: '解析失败，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  // 输入链接
  onInput(e) {
    this.setData({
      inputUrl: e.detail.value
    });
  },

  // 清空输入
  clearInput() {
    this.setData({
      inputUrl: '',
      videoInfo: null
    });
  },

  // 开始解析
  onParse() {
    this.parseVideo().then(() => {
      console.log('解析成功');
    }).catch((err) => {
      console.error('解析失败:', err);
    });
  },

  // 复制链接
  copyLink() {
    if (!this.data.videoInfo || !this.data.videoInfo.url) {
      wx.showToast({
        title: '暂无可复制的链接',
        icon: 'none'
      });
      return;
    }

    wx.setClipboardData({
      data: this.data.videoInfo.url,
      success: () => {
        wx.showToast({
          title: '链接已复制',
          icon: 'success'
        });
      }
    });
  },

  // 下载视频
  downloadVideo() {
    if (!this.data.currentVideo) {
      wx.showToast({
        title: '请先解析视频',
        icon: 'none'
      })
      return
    }

    this.startDownload()
  },

  // 开始下载
  startDownload() {
    if (!this.data.currentVideo || !this.data.currentVideo.url) {
      wx.showToast({
        title: '下载链接无效',
        icon: 'none'
      })
      return
    }

    this.setData({
      isDownloading: true,
      downloadProgress: 0
    })

    const downloadTask = wx.downloadFile({
      url: this.data.currentVideo.url,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveVideoToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '已保存到相册',
                icon: 'success'
              })
              this.setData({
                isDownloading: false,
                downloadProgress: 100
              })
              // 3秒后重置进度条
              setTimeout(() => {
                this.setData({
                  downloadProgress: 0
                })
              }, 3000)
            },
            fail: (error) => {
              this.setData({
                isDownloading: false,
                downloadProgress: 0
              })
              if (error.errMsg.includes('auth deny')) {
                this.requestSavePermission()
              } else {
                wx.showToast({
                  title: '保存失败',
                  icon: 'none'
                })
              }
            }
          })
        }
      },
      fail: () => {
        this.setData({
          isDownloading: false,
          downloadProgress: 0
        })
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        })
      }
    })

    // 监听下载进度
    downloadTask.onProgressUpdate((res) => {
      this.setData({
        downloadProgress: res.progress
      })
    })
  },

  // 保存视频到相册
  saveVideoToAlbum(tempFilePath) {
    // 检查权限
    wx.getSetting({
      success: (authStatus) => {
        if (!authStatus.authSetting['scope.writePhotosAlbum']) {
          this.requestSavePermission()
          return
        }
        
        // 保存视频
        wx.saveVideoToPhotosAlbum({
          filePath: tempFilePath,
          success: () => {
            wx.showToast({
              title: '已保存到相册',
              icon: 'success'
            })

            // 清除当前视频信息和输入框链接
            this.setData({
              videoInfo: null,
              currentVideo: null,
              inputUrl: '' // 清空输入框链接
            })
          },
          fail: (error) => {
            if (error.errMsg.includes('auth deny')) {
              this.requestSavePermission()
            } else if (error.errMsg.includes('saveVideoToPhotosAlbum:fail cancel')) {
              console.log('用户取消了保存操作')
            } else {
              wx.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          }
        })
      },
      fail: () => {
        wx.showToast({
          title: '获取权限失败',
          icon: 'none'
        })
      }
    })
  },

  // 请求保存权限
  requestSavePermission() {
    wx.showModal({
      title: '提示',
      content: '需要您授权保存到相册',
      confirmText: '去授权',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.writePhotosAlbum']) {
                wx.showToast({
                  title: '授权成功',
                  icon: 'success'
                })
              } else {
                wx.showToast({
                  title: '授权失败',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },

  // 提取最高清的视频
  getHighestQualityVideo(videoData) {
    if (!videoData.bit_rate || videoData.bit_rate.length === 0) {
      return null
    }

    // 按比特率排序，找到最高清的视频
    const sortedBitRate = videoData.bit_rate.sort((a, b) => {
      // 首先按照分辨率排序（1080p > 720p > 540p）
      const resA = parseInt(a.gear_name.match(/\d+/)[0])
      const resB = parseInt(b.gear_name.match(/\d+/)[0])
      if (resA !== resB) return resB - resA
      
      // 分辨率相同时按比特率排序
      return b.bit_rate - a.bit_rate
    })
    
    return sortedBitRate[0]
  },

  // 添加到历史记录
  addToHistory(videoInfo) {
    let historyList = wx.getStorageSync('videoHistory') || []
    const historyItem = {
      ...videoInfo,
      originalUrl: this.data.inputUrl // 保存原始输入的链接
    }
    
    // 检查是否已存在相同的视频，如果存在则更新
    const index = historyList.findIndex(item => item.url === videoInfo.url)
    if (index !== -1) {
      historyList[index] = historyItem
    } else {
      historyList.unshift(historyItem)
    }
    
    // 限制历史记录数量
    if (historyList.length > 20) {
      historyList = historyList.slice(0, 20)
    }
    
    wx.setStorageSync('videoHistory', historyList)
    this.setData({ historyList })
  },

  // 加载历史记录
  loadHistory() {
    const historyList = wx.getStorageSync('videoHistory') || []
    this.setData({ historyList })
  },

  // 清空历史记录
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空历史记录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('videoHistory')
          this.setData({ historyList: [] })
          wx.showToast({
            title: '已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  // 重新加载历史记录项
  reloadHistory(e) {
    const item = e.currentTarget.dataset.item
    // 如果有原始链接就使用原始链接，否则使用视频URL
    const inputUrl = item.originalUrl || item.url || ''
    
    this.setData({
      inputUrl: inputUrl,
      videoInfo: item,
      currentVideo: item
    })

    // 如果是旧的历史记录（没有originalUrl），则更新它
    if (!item.originalUrl) {
      const updatedItem = {
        ...item,
        originalUrl: item.url
      }
      let historyList = wx.getStorageSync('videoHistory') || []
      const index = historyList.findIndex(h => h.url === item.url)
      if (index !== -1) {
        historyList[index] = updatedItem
        wx.setStorageSync('videoHistory', historyList)
        this.setData({ historyList })
      }
    }
  },

  // 加载用户状态
  loadUserStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({
        isVipUser: userInfo.isVip || false,
        remainingCount: userInfo.remainingCount || 3
      })
    }
  },

  // 增加用户使用次数
  addUserCount(count) {
    const newCount = this.data.remainingCount + count
    wx.setStorageSync('remainingCount', newCount)
    this.setData({
      remainingCount: newCount
    })
    wx.showToast({
      title: `获得${count}次使用机会`,
      icon: 'success'
    })
  },

  // 检查是否可以使用功能
  checkCanUse() {
    if (this.data.isVipUser) {
      return true
    }
    return this.data.remainingCount > 0
  },

  // 手动粘贴
  pasteUrl() {
    try {
      const { data } = wx.getClipboardData()
      if (!data) {
        wx.showToast({
          title: '剪贴板为空',
          icon: 'none'
        })
        return
      }
      
      // 直接设置输入框的值，不做任何检查和弹窗
      this.setData({
        inputUrl: data
      })
    } catch (error) {
      console.error('粘贴失败:', error)
      wx.showToast({
        title: '粘贴失败',
        icon: 'none'
      })
    }
  },

  // 初始化广告
  initVideoAd() {
    if (!wx.createRewardedVideoAd) {
      console.log('当前版本不支持激励视频广告')
      return
    }

    this.videoAd = wx.createRewardedVideoAd({
      adUnitId: 'adunit-xxx' // 替换为您的广告单元ID
    })
    
    this.videoAd.onLoad(() => {
      console.log('激励视频广告加载成功')
      this.setData({ isAdLoaded: true })
    })
    
    this.videoAd.onError((err) => {
      console.log('激励视频广告加载失败', err)
      this.setData({ isAdLoaded: false })
      // 广告加载失败时，直接允许下载
      if (err.errCode === 1002) {
        this.handleAdError()
      }
    })
    
    this.videoAd.onClose((res) => {
      if (res && res.isEnded) {
        this.startDownload()
      } else {
        wx.showToast({
          title: '需要完整观看广告才能下载',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 处理广告错误
  handleAdError() {
    // 检查用户状态
    if (this.data.isVipUser) {
      this.startDownload()
      return
    }

    // 非VIP用户检查剩余次数
    if (this.data.remainingCount > 0) {
      wx.showModal({
        title: '提示',
        content: '广告加载失败，是否使用一次免费下载机会？',
        success: (res) => {
          if (res.confirm) {
            this.setData({
              remainingCount: this.data.remainingCount - 1
            })
            wx.setStorageSync('userInfo', {
              ...wx.getStorageSync('userInfo'),
              remainingCount: this.data.remainingCount
            })
            this.startDownload()
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '广告加载失败，您的免费下载次数已用完。开通VIP享无限下载特权！',
        confirmText: '开通VIP',
        cancelText: '暂不开通',
        success: (res) => {
          if (res.confirm) {
            // 跳转到VIP购买页面
            wx.navigateTo({
              url: '/pages/vip/vip'
            })
          }
        }
      })
    }
  },

  // 视频下载处理
  handleDownload: function(e) {
    const type = e.currentTarget.dataset.type;
    if (type === 'noWatermark') {
      this.downloadNoWatermark();
    } else {
      this.downloadNormal();
    }
  },

  // 普通下载（保持原有的下载逻辑）
  downloadNormal: function() {
    // 原有的下载代码...
  },

  // 切换分析面板显示状态
  toggleAnalysis() {
    this.setData({
      showAnalysis: !this.data.showAnalysis
    });
  },

  // 格式化数字
  formatNumber(num) {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + 'w';
    }
    return num;
  }
})